package tracker.model;

import com.db4o.query.Query

abstract class LazyQuery[QInterface, T](val criteria: List[Query=>Query]) extends Iterable[T] {
  
  def elements = {
    val initialQuery: Query = null
    val query = (criteria :\ initialQuery)((f, q)=>f(q))
    Db4oUtil.iterate[T](query)
  }
  
  def factory: List[Query=>Query]=>QInterface
  
  def constrain(c: Query=>Query) = factory(c :: criteria)
}


object Db4oUtil {
  def iterate[T](q: Query) = {
    val set = q.execute()
    new Iterator[T] {
      def hasNext = set.hasNext
      def next = set.next.asInstanceOf[T]
    }
  }  
}

